//
//  LoginViewController.m
//  DaDaBao
//
//  Created by user on 15/8/14.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "LoginViewController.h"
#import "FindPsdViewController.h"
#import "RegistViewController.h"
#import "LoginModel.h"

@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)UITextField * userTextField;//用户名
@property (nonatomic,strong)UITextField * psdTextField;//密码
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];

    
    [self createTheNavigationBar];//创建导航栏及相关控件
    
    [self createTheUserAndPsd];//创建用户名及密码输入控件，登录按钮，忘记密码按钮
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"noRegist" object:nil];
}
#pragma mark -------------创建导航栏及相关控件
-(void)createTheNavigationBar
{
    
    //    自定义navgationBar
    TopView *topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    [topView setTitile:@"用户登录"];
    [self.view addSubview:topView];
    //注册按钮
    UIButton * registBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 60, 30, 50, 30.0f)];
    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(buttonGoToRegistViewContrllerTapped:) forControlEvents:UIControlEventTouchUpInside];
    registBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:registBtn];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 50, 30.0f)];
    [backBtn setTitle:@"取消" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonGoBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [topView addSubview:backBtn];
}
#pragma mark -------------创建用户名及密码输入控件，登录按钮,忘记密码按钮
-(void)createTheUserAndPsd
{
    //用户名
    UIView * userView = [[UIView alloc]initWithFrame:CGRectMake(0, 64 + 10*HSCALE, SCREEN_WIDTH , 88*HSCALE)];
    userView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userView];
    
    UILabel * userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10*WSCALE, 2*HSCALE, 80*WSCALE, 40*HSCALE)];
    userNameLabel.text = @"用户名";
    userNameLabel.textColor = RGBA(99, 98, 99, 1);
    userNameLabel.textAlignment = NSTextAlignmentLeft;
    [userView addSubview:userNameLabel];
    
    _userTextField = [[UITextField alloc]initWithFrame:CGRectMake(80*WSCALE, 2*HSCALE, SCREEN_WIDTH - 110*WSCALE, 40*HSCALE)];
    _userTextField.placeholder = @"手机号";
    _userTextField.delegate = self;
    _userTextField.font = [UIFont systemFontOfSize:15.0f];
    _userTextField.keyboardType = UIKeyboardTypeNumberPad;

    [userView addSubview:_userTextField];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(10*WSCALE, 41*HSCALE, SCREEN_WIDTH - 20*WSCALE, 1*HSCALE)];
    lineView.backgroundColor = RGBA(240, 240, 240, 1);
    [userView addSubview:lineView];
    
    UILabel * psdLabel = [[UILabel alloc]initWithFrame:CGRectMake(10*WSCALE, 42*HSCALE, 50*WSCALE, 40*HSCALE)];
    psdLabel.text = @"密码";
    psdLabel.textColor = RGBA(99, 98, 99, 1);
    psdLabel.textAlignment = NSTextAlignmentLeft;
    [userView addSubview:psdLabel];
    
    _psdTextField = [[UITextField alloc]initWithFrame:CGRectMake(80*WSCALE, 42*HSCALE, SCREEN_WIDTH - 110*WSCALE, 40*HSCALE)];
    _psdTextField.delegate = self;
    _psdTextField.placeholder = @"请输入密码";
    _psdTextField.font = [UIFont systemFontOfSize:15.0f];
    _psdTextField.secureTextEntry = TRUE;
    [userView addSubview:_psdTextField];
    
    //登录按钮
    UIButton * loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 20*WSCALE, 35*HSCALE)];
    loginBtn.center = CGPointMake(self.view.center.x, 64+142.5*HSCALE);
    loginBtn.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
    loginBtn.layer.cornerRadius = 5;
    loginBtn.layer.masksToBounds = TRUE;
    loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19]; 
    [loginBtn setTitle:@"立即登录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(buttonLoginTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    //忘记密码？
    UIButton * findPsdBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 80*WSCALE, 64 + 165*HSCALE, 70*WSCALE, 30*HSCALE)];
    findPsdBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [findPsdBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    findPsdBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [findPsdBtn setTitleColor:RGBA(50, 154, 215, 1) forState:UIControlStateNormal];
    [findPsdBtn addTarget:self action:@selector(buttonFindPsdTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:findPsdBtn];
}
#pragma mark--------------忘记密码按钮绑定方法
-(void)buttonFindPsdTapped:(id)sender
{
    FindPsdViewController * vc = [[FindPsdViewController alloc]init];
    [self presentViewController:vc animated:TRUE completion:nil];
}
#pragma mark--------------登录按钮绑定方法
-(void)buttonLoginTapped:(id)sender
{
    if (_userTextField.text.length<=0)
    {
        ALERT_VIEW(@"用户名不能为空");
        return;
    }
    if (![self validateMobile:_userTextField.text])
    {
        ALERT_VIEW(@"用户名不合法");
        return;
    }
    if (_psdTextField.text.length<=0)
    {
        ALERT_VIEW(@"密码不能为空");
        return;
    }
    if (_psdTextField.text.length <6) {
        ALERT_VIEW(@"密码至少6位");
        return;
    }
    [self.view endEditing:TRUE];//键盘下去
  
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    
    [AppGlobalClass PostDataWithNSstring:PHONE_ISREGIST withDictionary:@{@"mobile":_userTextField.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:FALSE]])
        {
            [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
            NSString * string = [dictionary objectForKey:@"message"];
            ALERT_VIEW(string);
        }else
        {//注册的时候
            NSDictionary *dict = @{ @"userCd" : _userTextField.text, @"password":[AppGlobalClass md5:_psdTextField.text],@"driverType":@"iOS",@"versionNo":@"1.1"};
            [AppGlobalClass PostDataWithNSstring:LOGIN_URL withDictionary:dict success:^(NSDictionary *dictionary){
                if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
                {
                    LoginModel *loginModel = [[LoginModel alloc]initWithDictionary:[[[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"]firstObject]];
                    [[NSUserDefaults standardUserDefaults]setObject:_userTextField.text forKey:@"userCd"];
                    [[NSUserDefaults standardUserDefaults]setObject:[AppGlobalClass md5:_psdTextField.text] forKey:@"password"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.token forKey:@"token"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.idCardVStatus forKey:@"idCardVStatus"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.mobileVStatus forKey:@"mobileVStatus"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.payPasswordVStatus forKey:@"payPasswordVStatus"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.cardVStatus forKey:@"cardVStatus"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.mobile forKey:@"mobile"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.memberNo forKey:@"memberNo"];
                    [[NSUserDefaults standardUserDefaults]setObject:loginModel.memberType forKey:@"memberType"];
                    if([loginModel.idCardVStatus intValue] == 1)
                    {
                        [[NSUserDefaults standardUserDefaults]setObject:loginModel.realName forKey:@"realName"];
                    }
                    
                    [[NSUserDefaults standardUserDefaults]setValue:loginModel.payPasswordVStatus forKey:@"payPasswordVStatus"];
                    [[NSUserDefaults standardUserDefaults]synchronize];

                    [self dismissViewControllerAnimated:FALSE completion:^{
                        //登录成功后，进入设置手势界面
                        SetGestureLockViewController * vc = [[SetGestureLockViewController alloc]initWithGestureType:setGestureLock];
                        [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:vc                                                                                                    animated:TRUE completion:nil];
                    }];
                    
                }
                else
                {
                    ALERT_VIEW([dictionary objectForKey:@"message"]);
                }
                [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
            } failure:^(NSError *error){
                [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
            } networkerror:^(NSString *networkerror){
                [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
            }];

        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror) {
        [MBProgressHUD hideHUDForView:self.view animated:TRUE];
    }];
}
#pragma mark -------------注册按钮绑定方法
-(void)buttonGoToRegistViewContrllerTapped:(id)sender
{
    RegistViewController * vc = [[RegistViewController alloc]init];
    [self presentViewController:vc animated:TRUE completion:nil];
}
#pragma mark -------------返回按钮绑定方法
-(void)buttonGoBackTapped:(id)sender
{
    [self dismissViewControllerAnimated:TRUE completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark-------------正则表达式
//邮箱
-(BOOL)validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
//手机号码验证
-(BOOL)validateMobile:(NSString *)mobile
{
    //手机号以1开头，10个 \d 数字字符
    NSString *phoneRegex = @"^(1[0-9])\\d{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}
//密码
- (BOOL) validatePassword:(NSString *)passWord
{
    //    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$"; 密码是数字或者字母
    NSString *passWordRegex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";//密码是数字或者字母，且不能全部是数字，全部是字母
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}
#pragma mark--------textFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (_userTextField == textField)
    {
        NSString *a = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (a.length>11) {
            
            return NO;
        }
        return YES;
    }else
    {
        NSString *a = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (a.length>30) {
            
            return NO;
        }
        return YES;
    }
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
